package com.cp.dateformat;


import com.google.common.collect.Lists;
import lombok.SneakyThrows;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * 时间格式增强, 匹配更多的时间格式类型
 *
 * @author YangXiaoLong
 * 2021/8/27 13:56
 */
public class CpDateTimeDateFormat extends SimpleDateFormat {

    public final static String FORMAT_DEFAULT_T = "yyyy-MM-dd'T'HH:mm:ssX";
    public final static String FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";
    public final static String FORMAT_DEFAULT2 = "yyyy/MM/dd HH:mm:ss";
    public final static String FORMAT_DEFAULT_MILLIS = "yyyy-MM-dd HH:mm:ss.SSS";
    public final static String FORMAT_DATE = "yyyy-MM-dd";
    public final static String FORMAT_DATE2 = "yyyyMMdd";
    public final static String FORMAT_DATE3 = "yyyy/MM/dd";
    public final static String FORMAT_DATE_01 = "yyyy-MM-01";
    public final static String FORMAT_MONTH = "yyyy-MM";
    public final static String FORMAT_MONTH2 = "yyyyMM";
    public final static String FORMAT_MONTH3 = "yyyy/MM";
    public final static String FORMAT_DATETIME = "yyyy-MM-dd HH:mm";
    public final static String FORMAT_DATETIME2 = "yyyyMMddHHmmss";
    public final static String FORMAT_DATETIME3 = "yyyyMMddHHmm";

    private final ArrayList<String> DATE_FORMAT_LiST = Lists.newArrayList(
            FORMAT_DEFAULT_T,
            FORMAT_DEFAULT,
            FORMAT_DEFAULT_MILLIS,
            FORMAT_DATE,
            FORMAT_DATE2,
            FORMAT_DATE3,
            FORMAT_DATE_01,
            FORMAT_MONTH,
            FORMAT_MONTH2,
            FORMAT_MONTH3,
            FORMAT_DATETIME,
            FORMAT_DATETIME2,
            FORMAT_DEFAULT2,
            FORMAT_DATETIME3
    );

    @Override
    @SneakyThrows
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
        return new StringBuffer(DateFormatUtils.format(date, FORMAT_DEFAULT));
    }

    @Override
    @SneakyThrows
    public Date parse(String source) {
        return DateUtils.parseDate(source, DATE_FORMAT_LiST.toArray(new String[0]));
    }
}
